package com.tchhy.provider.rx

import com.google.gson.JsonParseException
import com.tchhy.provider.URLConstant
import org.json.JSONException
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.ConnectException
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.text.ParseException

/**
 * Describe: 网络异常相关
 *
 * Author: wfy
 *
 */
class RxErrorHandle(val it: Throwable) {
    fun error(): BaseException {
        it.printStackTrace()
        return when (it) {
            is HttpException -> {
                BaseException(
                    URLConstant.CODE_SERVICE_EXCEPTION,
                    "网络异常"
                )
            }
            is SocketTimeoutException -> {
                /*
                    链接或读取超时
                 */
                BaseException(
                    URLConstant.CODE_SERVICE_SOCKET_OUTTIME,
                    "网络连接超时"
                )
            }
            is SocketException -> {
                /*
                    创建或访问套接字是否存在错误
                 */
                BaseException(
                    URLConstant.CODE_SERVICE_EXCEPTION,
                    "网络异常"
                )
            }
            is UnknownHostException -> {
                /*
                    IP地址无法确定
                 */
                BaseException(
                    URLConstant.CODE_SERVICE_UNKNOWN_HOST,
                    "连接错误"
                )
            }
            is BaseException -> {
                it
            }
            is InterruptedIOException -> {
                BaseException(
                    URLConstant.CODE_SERVICE_UNKNOWN_HOST,
                    "连接超时"
                )
            }
            is ConnectException -> {
                /*
                    尝试连接远程地址和端口套接字时发生错误到。
                    通常是连接被远程拒绝（例如，没有进程正在监听）
                 */
                BaseException(
                    URLConstant.CODE_SERVICE_UNAVAILABLE,
                    "连接错误"
                )
            }
            is JsonParseException -> {
                BaseException(
                    URLConstant.CODE_SERVICE_UNAVAILABLE,
                    "解析错误"
                )
            }
            is JSONException -> {
                BaseException(
                    URLConstant.CODE_SERVICE_UNAVAILABLE,
                    "解析错误"
                )
            }
            is ParseException -> {
                BaseException(
                    URLConstant.CODE_SERVICE_UNAVAILABLE,
                    "解析错误"
                )
            }
            else -> {
                it.printStackTrace()
                BaseException(
                    URLConstant.CODE_SERVICE_UNKONW_ERROR,
                    "未知错误"
                )
            }
        }
    }
}